public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val = val;
        }
    }

    TreeNode root = null;

    public boolean search(int val){
        TreeNode cur = root;
        if(cur.val < val){
            cur = cur.right;
        }else if(cur.val > val){
            cur = cur.left;
        }else {
            return true;
        }

        return false;
    }

    public boolean add(int val) {//插入
        TreeNode treeNode = new TreeNode(val);
        if(root == null){
            root = treeNode;
            return true;
        }

        TreeNode cur = root;
        TreeNode parent = null;

        while (cur != null) {
            if (cur.val < val) {

                parent = cur;//记录cur的父亲节点
                cur = cur.right;
            } else if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                return false;
            }
        }


        if(parent.val < val){
            parent.right = treeNode;
        }else {
            parent.left = treeNode;
        }

        return true;
    }

    //删除节点
    public void remove(int val){
        TreeNode cur = root;
        TreeNode parent = null;

        while (cur != null) {
            if (cur.val < val) {

                parent = cur;//记录cur的父亲节点
                cur = cur.right;
            } else if (cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {//找到了删除的节点
                //删除节点
                removeNode(parent,cur);
            }
        }
    }

    public void removeNode(TreeNode parent,TreeNode cur){//分情况讨论
        if(cur.left == null){
            if (cur == root) {

                cur = cur.right;
            }else if(cur == parent.left){

                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if(cur.right == null){

            if(cur == root){

                cur = cur.left;
            }else if(cur == parent.left){

                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            //cur的左右都不为空，用到替罪羊（用左树的最右节点或者右树的最左边节点）
            TreeNode target = cur.right;
            TreeNode targetParent = cur;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if(target == targetParent.left) {

                targetParent.left = target.right;
            }else if(target == targetParent.right){

                targetParent.right = target.right;
            }
        }
    }

}
